package com.lingjtx.common.influx.client;

import com.lingjtx.common.influx.common.InfluxMappedStatement;
import com.lingjtx.common.influx.common.XmlMapperParser;
import com.lingjtx.common.influx.config.InfluxProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

@Component
public class InfluxSession {

    private static final Logger log = LoggerFactory.getLogger(InfluxSession.class);

    private final Map<String, InfluxMappedStatement> mappedStatements = new HashMap<>();
    private final InfluxQueryExecutor executor;

    public InfluxSession(InfluxQueryExecutor executor, InfluxProperties properties) {
        this.executor = executor;
        loadXml(properties.getMapperLocations());
    }

    private void loadXml(String pattern) {
        try {
            Resource[] resources = new PathMatchingResourcePatternResolver().getResources(pattern);
            XmlMapperParser parser = new XmlMapperParser();
            for (Resource res : resources) {
                mappedStatements.putAll(parser.parse(res));
            }
        } catch (Exception e) {
            log.error("Influx 加载 xml mapper 异常：{}", e.getMessage());
        }
    }


    public <T> T getMapper(Class<T> mapperClass) {
        if (!mapperClass.isInterface()) {
            throw new IllegalArgumentException("The provided class must be an interface: " + mapperClass);
        }
        Object proxy = Proxy.newProxyInstance(mapperClass.getClassLoader(),
                new Class[]{mapperClass},
                new InfluxMapperProxy(mapperClass, mappedStatements, executor));
        return mapperClass.cast(proxy);
    }
}
